﻿
package org.hyy.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import sun.misc.BASE64Decoder;

/**
 * Utility for string.
 *
 */
public class StringUtil {
    public static final String dateFormat = "yyyy-MM-dd";
    public static final String dateDotFormat = "yyyy.MM.dd";
    public static final String timeFormat = "yyyy-MM-dd HH:mm:ss";
    public static final String timeFormat_withTZ = "yyyy-MM-dd HH:mm:ss z";
    public static final String SQL_ESCAPE_ORA = " ESCAPE '\\' ";
	// 过滤通过页面表单提交的字符
	private static String[][] FilterChars = { { "<", "＜" }, { ">", "＞" },
			{ "\"", "＼" }, { "&", "＆" },
			{ "/", "&#47;" }, { "\\", "&#92;" }, { "\n", "<br>" } };

	// 过滤通过javascript脚本处理并提交的字符
	private static String[][] FilterScriptChars = { { "\n", "\'+\'\\n\'+\'" },
			{ "\r", " " }, { "\\", "\'+\'\\\\\'+\'" },
			{ "\'", "\'+\'\\\'\'+\'" } };
	
	private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签
	/**
	 * 过滤字符串里的的特殊字符
	 * 
	 * @param str
	 *            要过滤的字符串
	 * @return 过滤后的字符串
	 */
	public static String stringFilter(String str) {
		String[] str_arr = stringSpilit(str, "");
		for (int i = 0; i < str_arr.length; i++) {
			for (int j = 0; j < FilterChars.length; j++) {
				if (FilterChars[j][0].equals(str_arr[i]))
					str_arr[i] = FilterChars[j][1];
			}
		}
		return (stringConnect(str_arr, "")).trim();
	}
	
	/**
	 * 过滤脚本中的特殊字符（包括回车符(\n)和换行符(\r)）
	 * 
	 * @param str
	 *            要进行过滤的字符串
	 * @return 过滤后的字符串
	 */
	public static String stringFilterScriptChar(String str) {
		String[] str_arr = stringSpilit(str, "");
		for (int i = 0; i < str_arr.length; i++) {
			for (int j = 0; j < FilterScriptChars.length; j++) {
				if (FilterScriptChars[j][0].equals(str_arr[i]))
					str_arr[i] = FilterScriptChars[j][1];
			}
		}
		return (stringConnect(str_arr, "")).trim();
	}
	
	/**
	 * 过滤以<开始，>结尾的标签
	 * @param str
	 * @return
	 */
	public static String filterHtml(String str) {
		Pattern pattern = Pattern.compile(regxpForHtml);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}
	
	/**
	 * 分割字符串
	 * 
	 * @param str
	 *            要分割的字符串
	 * @param spilit_sign
	 *            字符串的分割标志
	 * @return 分割后得到的字符串数组
	 */
	public static String[] stringSpilit(String str, String spilit_sign) {
		String[] spilit_string = str.split(spilit_sign);
		if (spilit_string[0].equals("")) {
			String[] new_string = new String[spilit_string.length - 1];
			for (int i = 1; i < spilit_string.length; i++)
				new_string[i - 1] = spilit_string[i];
			return new_string;
		} else
			return spilit_string;
	}
	
	public static String stringConnect(String[] strings, String spilit_sign) {
		String str = "";
		for (int i = 0; i < strings.length; i++) {
			str += strings[i] + spilit_sign;
		}
		return str;
	}
    
    public static String sqlLikeReplaceOra(String s){
    	s = StringUtil.replace(s, "'", "''");
    	s = StringUtil.replace(s, "_", "\\_");
    	s = StringUtil.replace(s, "%", "\\%");
    	return s;
    }
    public static String sqlEqualReplaceOra(String s){
    	s = StringUtil.replace(s, "'", "''");
    	return s;
    }
    
    /**
     * Removes all occurrences of character <B>c</B> from String <B>s</B>.
     *
     * @param s input string.
     * @param c character to remove.
     * @return the resulting string, or null in case of a null argument.
     */
    public static String removeChar(String s, char c) {

        if (s == null || s.length() == 0)
			return s;

        if (s.indexOf(c) == -1)
			return s;

        StringBuffer buf = new StringBuffer(s.length());
        int pos;

        for (pos = 0; pos < s.length(); pos++) {
            if (s.charAt(pos) != c) {
                buf.append(s.charAt(pos));
            }
        }

        return buf.toString();
    }

    /**
     * Removes all occurrences of every character in String
     * <B>s2</B> from String <B>s1</B>.
     *
     * @param s1 input string.
     * @param s2 string containing characters to remove.
     * @return the resulting string, or null in case of a null s1.
     */
    public static String removeChar(String s1, String s2) {

        if (s1 == null)
			return s1;

        StringBuffer buf = new StringBuffer(s1.length());
        int pos;

        for (pos = 0; pos < s1.length(); pos++) {
            if (s2.indexOf(s1.charAt(pos)) == -1) {
                buf.append(s1.charAt(pos));
            }
        }

        return buf.toString();
    }

    /**
     * Removes all occurrences of every character <I>not</I> in String
     * <B>s2</B> from String <B>s1</B>.
     *
     * @param s1 input string.
     * @param s2 string containing characters to keep.
     * @return the resulting string, or null in case of a null s1.
     */
    public static String keepChars(String s1, String s2) {

        if (s1 == null)
			return null;

        if (s2 == null)
			return new String(s1);

        StringBuffer buf = new StringBuffer(s1.length());
        int pos;

        for (pos = 0; pos < s1.length(); pos++) {
            if (s2.indexOf(s1.charAt(pos)) != -1) {
                buf.append(s1.charAt(pos));
            }
        }

        return buf.toString();
    }

    /**
     * Replaces all occurrences of every string <b>source</b> in String
     * <B>original</B> to String <B>target</B>.
     *
     * @param original input string.
     * @param source string containing characters to be replaced.
     * @param target string containing characters to replace.
     * @return the resulting string, or null in case of a null s1.
     */
    public static String replace(
            String original,
            String source,
            String target) {
        if (isEmpty(original))
			return null;
        if (original.indexOf(source) < 0)
			return original;

        StringBuffer result = new StringBuffer();

        int indexPos, beginPos = 0;

        while ((indexPos = original.indexOf(source, beginPos)) >= 0) {
            result.append(original.substring(beginPos, indexPos) + target);
            beginPos = indexPos + source.length();
        }

        result.append(original.substring(beginPos));
        return result.toString();
    }

    /**
     * Duplicates each single quote in String <B>s</B>, making
     * the result suitable for use as a quoted literal in a SQL query.
     *
     * @param s input string.
     */
    public static String escapeQuotes(String s) {
        if (s.indexOf('\'') == -1)
			return s;

        StringBuffer buf = new StringBuffer(s.length() + 4); // guessing
        int pos;

        for (pos = 0; pos < s.length(); pos++) {
            buf.append(s.charAt(pos));
            if (s.charAt(pos) == '\'') {
                buf.append('\'');
            }
        }

        return buf.toString();
    }

    /**
     * Return true if the string passed represents a null string (all white
     * space or an explicit null)
     *
     * @param pVal string to check for the "null" property
     */
    public static boolean isEmpty(String pVal) {
        return pVal == null || pVal.trim().length() == 0;
    }

    public static boolean isNotEmpty(String pVal){
        return pVal != null && pVal.trim().length() > 0;
    }
    
    public static boolean isNotEmpty(String[] pVal){
        return pVal != null && pVal.length > 0;
    }
    
    public static boolean isEmpty(String[] pVal){
        return pVal == null || pVal.length == 0;
    }
    
    /**
     * Perform the equivalent of String.trim(), but, in case of a null
     * argument, simply return null.  Useful when cleaning up form input.
     */
    public static String trim(String pVal) {
        if (pVal != null)
			return pVal.trim();
		else
			return null;
    }

    /**
     * Analogous to good old join from Perl (why is this not in Java?!!).
     * join(new String[] {"a", "b", "c"}, "|") => "a|b|c"
     *
     * @param strArray An array of Strings
     * @param separator A string which will be interpolated between them.
     * @return A string of all the elements of the array concatenated,
     * with separator between each.  If the initial array is null,
     * null is returned
     **/
    public static String join(String[] strArray, String separator) {

        if (strArray == null)
			return null;

        StringBuffer results = new StringBuffer();

        for (int i = 0; i < strArray.length; i++) {
            if (i > 0) {
                results.append(separator);
            }
            results.append(strArray[i]);
        }
        return results.toString();
    }

    /**
     * Analogous to good old join from Perl (why is this not in Java?!!).
     * join(new String[] {"a", "b", "c"}, "|") => "a|b|c"
     *
     * @param strVector A Vector of Strings
     * @param separator A string which will be interpolated between them.
     * @return A string of all the elements of the array concatenated,
     * with separator between each.  If the initial array is null,
     * null is returned
     **/
    public static String join(Vector strVector, String separator) {

        if (strVector == null)
			return null;

        StringBuffer results = new StringBuffer();

        for (int i = 0; i < strVector.size(); i++) {
            if (i > 0) {
                results.append(separator);
            }
            results.append((String) strVector.elementAt(i));
        }
        return results.toString();
    }

    /**
     * Analogous to good old split from Perl.
     * split("|,", "a|b,c") => new String[] {"a", "b", "c"}
     *
     * @param separatorChars A string of characters, anyone one of which
     * delimits the substrings.
     * @param str The string which contains the substrings
     * @return An array.  Returns null if passed in null.
     **/
    public static String[] split(String separatorChars, String str) {

        if (str == null)
			return null;

        StringTokenizer st = new StringTokenizer(str, separatorChars, false);

        String[] results = new String[st.countTokens()];
        int i = 0;
        while (st.hasMoreTokens()) {
            results[i++] = st.nextToken();
        }

        return results;
    }

    public static void main(String[] args) {

        String[] vals = split(",", "aa adfja adfas,adfa dfa");
        for (int i = 0; i < vals.length; i++) {
            System.out.println("'" + vals[i] + "'");
        }
    }

    public static int getArrayIndex(String s, String[] ss) {

        if (ss == null || ss.length == 0)
			return -1;

        int index = -1;

        for (int i = 0; i < ss.length; i++) {
            if (ss[i].equalsIgnoreCase(s)) {
                index = i;
                break;
            }

        }

        return index;
    }

    public static Date stringToDate(String dateString) {

        return stringToDate(dateString, dateFormat);

    }

    public static Date stringToDate(String dateString, String format) {

        Date date = null;
        if (dateString == null)
			return null;

        if (dateString.length() > 10) {
            format = format + " kk:mm:ss";
        }
        final SimpleDateFormat df = new SimpleDateFormat(format);

        try {
            date = df.parse(dateString);
        } catch (java.text.ParseException e) {
            System.out.println(dateString + "  " + format);
            date = null;

        }
        return date;

    }

    public static String databaseValue(String value, String type) {
        //System.out.println(value + " " + type);
        if (isEmpty(value))
			return "null";
        if ("Date".equalsIgnoreCase(type))
			return "to_date('" + value + "', dateFormat)";
		else if (
                "String".equalsIgnoreCase(type) || "Char".equalsIgnoreCase(type))
			return "'" + escapeQuotes(value) + "'";
		else
			return value;
    }

    public static String dateToString(Date date) {

        return dateToString(date, dateFormat);
    }

    public static String dateToString(Date date, String format) {

        final SimpleDateFormat df = new SimpleDateFormat(format);

        try {
            return date == null ? "" : df.format(date);
        } catch (Exception e) {
            System.out.println(date);
            return null;
        }

    }

    public static String dateToString(Calendar date) {

        final SimpleDateFormat df = new SimpleDateFormat(dateFormat);

        try {
            return date == null ? "" : df.format(date.getTime());
        } catch (Exception e) {
            System.out.println(date);
            return null;
        }

    }

    public static String dateTimeToString(Calendar date) {

        final SimpleDateFormat df = new SimpleDateFormat(timeFormat);

        try {
            return date == null ? "" : df.format(date.getTime());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }
    
   public static String dateTimeToStringWithTZ(Calendar date, TimeZone tz) {

       final SimpleDateFormat df = new SimpleDateFormat(timeFormat_withTZ);
        df.setTimeZone(tz);
        try {
            return date == null ? "" : df.format(date.getTime());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }
    

    public static boolean yNToboolean(String yn) {

        return "Y".equalsIgnoreCase(yn) ? true : false;
    }
    
    public static String yNToboolean(boolean yn) {

        return yn ? "Y" : "N";
    }

    public static boolean stringToBoolean(String yn) {
        if(!isEmpty(yn)) {
           if(yn.toLowerCase().equals("true"))
			return true;
		else
			return false;
        }
        return false;
    }
    
    public static Boolean yNToBoolean(String yn) {
        if(!isEmpty(yn)) {
           if(yn.equals("Y"))
			return Boolean.TRUE;
		else
			return Boolean.FALSE;
        }
        return null;
    }

    public static String yNToBoolean(Boolean yn) {
        String ret = null;
        if(yn != null) {
            if (yn.equals(Boolean.TRUE)) {
                ret = "Y";
            }
            else {
                ret = "N";
            }
        }
        else {
            ret = "";
        }
        return ret;
    }

    public static String escapeXML(String s) {
        StringBuffer str = new StringBuffer();
        int len = (s != null) ? s.length() : 0;
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '<':
                str.append("&lt;");
                break;
            case '>':
                str.append("&gt;");
                break;
            case '&':
                str.append("&amp;");
                break;
            case '"':
                str.append("&quot;");
                break;
            case '\'':
                str.append("&apos;");
                break;
            default:
                str.append(ch);
            }
        }
        return str.toString();
    }

    public static String supplement(int value, char supp, int num) {
        String v = String.valueOf(value);
        if (v.length() >= num)
			return v;

        StringBuffer buf = new StringBuffer(v);
        while (buf.length() < num) {
            buf.insert(0, supp);
        }
        return buf.toString();
    }

    public static String capitalizeWord(String string, String separator) {

        String[] arrString = split(separator, string);

        for (int i = 0; i < arrString.length; i++) {
            if (arrString[i].length() <= 1) {
                arrString[i] = arrString[i].toUpperCase();
            } else {
                arrString[i] =
                        arrString[i].substring(0, 1).toUpperCase()
                        + arrString[i].substring(1).toLowerCase();
            }

        }
        return join(arrString, separator);
    }

    public static String getDisplayForString(String str) {
        return (str == null ? "" : str.trim());
    }

    public static String getDisplayForInteger(Integer Int) {
        return (Int == null ? "" : Int.toString());
    }

    public static String getDisplayForint(int Int) {
        return String.valueOf(Int);
    }

    public static String getDisplayForLong(Long number) {
        return (number == null ? "" : number.toString());
    }

    public static Long string2Long(String str) {
        if (str != null && str.equals("")) {
            str = null;
        }
        return (str == null ? null : new Long(Long.parseLong(str)));
    }
    
    public static long string2long(String str) {
        if (str != null && str.equals("")) {
            str = null;
        }
        return Long.parseLong(str);
    }

    public static Integer string2Integer(String str) {
        if (str != null && str.equals("")) {
            str = null;
        }
        return (str == null ? null : new Integer(Integer.parseInt(str)));
    }

    public static Calendar string2Date(String str) {
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
        Date date = null;
        if (!isEmpty(str)) {
            try {
                date = formatter.parse(str);
            } catch (ParseException e) {}
        }
        //System.out.println("in util:" + date);
        Calendar cal = null;
        if (date != null) {
            cal = GregorianCalendar.getInstance();
            cal.setTime(date);
        }
        return cal;
    }
    
    public static Calendar stringdot2Date(String str) {
        SimpleDateFormat formatter = new SimpleDateFormat(dateDotFormat);
        Date date = null;
        if (!isEmpty(str)) {
            try {
                date = formatter.parse(str);
            } catch (ParseException e) {}
        }
        //System.out.println("in util:" + date);
        Calendar cal = null;
        if (date != null) {
            cal = GregorianCalendar.getInstance();
            cal.setTime(date);
        }
        return cal;
    }
    
    public static Calendar string2Date(String str, String _dateFormat ) {
        SimpleDateFormat formatter = new SimpleDateFormat(_dateFormat);
        Date date = null;
        if (!isEmpty(str)) {
            try {
                date = formatter.parse(str);
            } catch (ParseException e) {}
        }
        //System.out.println("in util:" + date);
        Calendar cal = null;
        if (date != null) {
            cal = GregorianCalendar.getInstance();
            cal.setTime(date);
        }
        return cal;
    }

    public static Calendar string2DateTime(String str) {
        SimpleDateFormat formatter = new SimpleDateFormat(timeFormat);
        Date date = null;
        if (!isEmpty(str)) {
            try {
                date = formatter.parse(str);
            } catch (ParseException e) {}
        }
        Calendar cal = null;
        if (date != null) {
            cal = GregorianCalendar.getInstance();
            cal.setTime(date);
        }
        return cal;
    }

    public static Calendar string2DateTimeWithTZ(String str, TimeZone tz) {
        SimpleDateFormat formatter = new SimpleDateFormat(timeFormat);
        formatter.setTimeZone(tz);
        Date date = null;
        if (!isEmpty(str)) {
            try {
                date = formatter.parse(str);
            } catch (ParseException e) {}
        }
        Calendar cal = null;
        if (date != null) {
            cal = GregorianCalendar.getInstance(tz);
            cal.setTime(date);
        }
        return cal;
    }
    
    public static String dateTime2StringWithClientTZ(Calendar date, String tz) {
        Calendar calendar = StringUtil.string2DateTimeWithTZ(StringUtil.dateTimeToString(date), date.getTimeZone());
         String time = StringUtil.dateTimeToStringWithTZ(calendar, TimeZone.getTimeZone(tz));
         return time;
    }
    
    public static int string2int(String str) {
        if (str != null && str.equals("")) {
            str = null;
        }
        return Integer.parseInt(str);
    }

    public static String[] getDisplayForIntegerList(List list) {
        String[] result = null;
        if (list == null) {
            result = new String[0];
        } else {
            result = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                result[i] = ((Integer) list.get(i)).toString();
            }
        }
        return result;
    }

    public static List stringArrayToIntgerList(String[] array) {
        List result = new java.util.ArrayList();
        if (array != null) {
            for (int i = 0; i < array.length; i++) {
                Integer value = new Integer(array[i]);
                result.add(value);
            }
        }
        return result;
    }
    
    public static List stringArrayToLongList(String[] array) {
        List result = new java.util.ArrayList();
        if (array != null) {
            for (int i = 0; i < array.length; i++) {
                Long value = new Long(array[i]);
                result.add(value);
            }
        }
        return result;
    }
    
    public static long[] stringArrayTolongArray(String[] array) {
        if(array == null) return null;
        if(array.length == 1 && ("".equals(array[0]) || array[0] == null)) return null;
        long[] result = new long[array.length];
        for (int i = 0; i < array.length; i++) {
            long value = string2Long(array[i]) == null ? 0 : string2Long(array[i]).longValue();
            result[i] = value;
        }
        return result;
    }


    public static String encryptPass(String plainText) {
        //small tools from qiao to encrypt the password using
        //one-way hash algorithm

        //no encrypt during testing period

//        if (true)
//			return plainText;

        StringBuffer hexString = new StringBuffer();
        try {

            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(plainText.getBytes());
            byte messageDigest[] = algorithm.digest();

            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                //whether appending the leading '0' or not
                //if(hex.length()==1) hexString.append('0');
                hexString.append(hex);
            }
        } catch (NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        }
        return hexString.toString();
    }

    public static String decryptPWBDigest(String ciphertext, String password) throws
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException,
            NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
            IllegalStateException, IOException {
        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;

        // Salt
        byte[] salt = {
                      (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
                      (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
        };

        // Iteration count
        int count = 20;

        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);

        // Transfer user password as char array and convert
        // it into a SecretKey object, using a PBE key
        // factory.
        pbeKeySpec = new PBEKeySpec(password.toCharArray());
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        // Our cleartext
        byte[] cleartext = (new BASE64Decoder()).decodeBuffer(ciphertext);

        // Encrypt the cleartext
        byte[] plaintext = pbeCipher.doFinal(cleartext);

        return new String(plaintext);

    }

    public static String RC4(String content, String password) throws
            UnsupportedEncodingException {
        int i;
        short tmp;
        byte keyBytes[] = password.getBytes();
        short cypherBytes[] = new short[256];
        if (password.length() == 0)
			return null;
        if (content.length() == 0)
			return null;
        for (i = 0; i < 256; i++) {
            cypherBytes[i] = (short) i;
        }
        int jump = 0;
        for (i = 0; i < 256; ++i) {
            jump = ((jump + cypherBytes[i] + keyBytes[i % password.length()]) &
                    0xFF) % 256;
            tmp = cypherBytes[i];
            //System.out.println(i + " - " + jump + "  -  " + tmp + "  -  " + cypherBytes[i] + " - " + cypherBytes[jump]);
            cypherBytes[i] = cypherBytes[jump];
            cypherBytes[jump] = tmp;
        }
        i = 0;
        jump = 0;
        byte resultArray[] = content.getBytes();
        int j = 0;
        for (int x = 0; x < resultArray.length; x++) {
            i = (i + 1) % 256;
            jump = (jump + cypherBytes[i] & 0xFF) % 256;
            //System.out.println(x + " - " + i + "  -  " + jump + "  -  " + cypherBytes[i]);
            tmp = cypherBytes[i];
            cypherBytes[i] = cypherBytes[jump];
            cypherBytes[jump] = tmp;
            j = ((cypherBytes[i] + cypherBytes[jump])) % 256;
            resultArray[x] = (byte) ((resultArray[x] ^ (cypherBytes[j])) & 0xFF);
        }
        String encryContent = new String(resultArray);
        return encryContent;
    }

    public static byte[] RC4(byte[] content, int length, String password) throws
            UnsupportedEncodingException {
        int i;
        short tmp;
        byte keyBytes[] = password.getBytes();
        short cypherBytes[] = new short[256];
        if (password.length() == 0)
			return null;
        if (content.length == 0)
			return null;
        for (i = 0; i < 256; i++) {
            cypherBytes[i] = (short) i;
        }
        int jump = 0;
        for (i = 0; i < 256; ++i) {
            jump = ((jump + cypherBytes[i] + keyBytes[i % password.length()]) &
                    0xFF) % 256;
            tmp = cypherBytes[i];
            //System.out.println(i + " - " + jump + "  -  " + tmp + "  -  " + cypherBytes[i] + " - " + cypherBytes[jump]);
            cypherBytes[i] = cypherBytes[jump];
            cypherBytes[jump] = tmp;
        }
        i = 0;
        jump = 0;
        byte resultArray[] = new byte[content.length];
        int j = 0;
        for (int x = 0; x < length; x++) {
            i = (i + 1) % 256;
            jump = (jump + cypherBytes[i] & 0xFF) % 256;
            //System.out.println(x + " - " + i + "  -  " + jump + "  -  " + cypherBytes[i]);
            tmp = cypherBytes[i];
            cypherBytes[i] = cypherBytes[jump];
            cypherBytes[jump] = tmp;
            j = ((cypherBytes[i] + cypherBytes[jump])) % 256;
            resultArray[x] = (byte) ((content[x] ^ (cypherBytes[j])) & 0xFF);
        }
        return resultArray;
    }

    /**
     * Change millis time to second.
     * @param timeInMillis
     * @return
     */
    public static String timeMillis2Second(long timeInMillis){
        return "" + ((float)timeInMillis / 1000 );
    }

    public static String truncate(String str, int size) {
        String ret = "";
        if(str != null) {
            if(str.length() > size) {
                ret = str.substring(0, size);
            }
            else {
                ret = str;
            }
        }
        return ret;
    }
    
    public static String double2Percentage( double percent ){
        NumberFormat df = new DecimalFormat("##0.0%");
        return (df.format(percent));
    }
    
    public static String double2String (double data) {
    	DecimalFormat df = new DecimalFormat("0.##");
    	return df.format(data);
    }


    public static Date getDateBegin(Calendar cal) {
        Date date = new Date();
   //     cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 00);
        cal.set(Calendar.MINUTE, 00);
        cal.set(Calendar.SECOND, 00);
        date = cal.getTime();
        return date;
    }
    
    public static Date getDateBegin(String _cal) {
    	Calendar cal = StringUtil.string2Date(_cal);
    	return StringUtil.getDateBegin(cal);
    } 
    public static Date getDateEnd(Calendar cal) {
        Date date = new Date();
  //      cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        date = cal.getTime();
        return date;
    }
    
    public static Date getDateEnd(String _cal) {
    	Calendar cal = StringUtil.string2Date(_cal);
        return StringUtil.getDateEnd(cal);
    } 
    
    public static String getTimeZoneID(String timeZoneString){
        String timeZoneID = null;
        String hourString = "";
        String minStirng = "";
        boolean isPositive = true;
        if(timeZoneString.startsWith("-")){
              isPositive = false;
              timeZoneString = timeZoneString.substring(1);
        }            
        int index = timeZoneString.indexOf(".");
        if(index<0){
            hourString = timeZoneString;
        }else{
            hourString = timeZoneString.substring(0,index);
            minStirng = timeZoneString.substring(index+1); 
        }
         if (minStirng.indexOf(".")>-1)
			return null;
		else {
             if(isPositive){
                 timeZoneID = "GMT+" + hourString + ":"; 
             }else{
                 timeZoneID = "GMT-" + hourString + ":";
             }
             if(minStirng != ""){
                 if( StringUtil.string2int(minStirng) !=5)
					return null;
				else {
                     timeZoneID += "30";
                 }
             } else {
                 timeZoneID += "00";
             }
         }        
         return timeZoneID;        
    }
    
	public static String generateRandomASCIIStr(int len) {
		Random rd = new Random(Calendar.getInstance().getTimeInMillis());
		StringBuilder strBuilder = new StringBuilder();
		for (int i = 0; i < len; i++) {
			boolean flag = rd.nextBoolean();
			char temp;
			if (flag) {
				temp = (char) (rd.nextInt(26) + 'a');
			} else {
				temp = (char) (rd.nextInt(26) + 'A');
			}
			strBuilder.append(temp);
		}
		return strBuilder.toString();
	}

	public static boolean isDigitString(String str) {
		boolean flag=true;
		for(int i=0;i<str.length();i++){
			if (false == Character.isDigit(str.charAt(i))) {
				flag = false;
			}
		}
		return flag;
	}
	
	//两个时间天数差
	public static int differInTwoCalendar(Calendar timeBefore, Calendar timeAfter) {
		long after = timeAfter.getTimeInMillis();
		long before = timeBefore.getTimeInMillis();
		long differ = (after - before)/(1000 * 60 * 60 * 24);
		return (int)differ;
	}
	
	//两个时间小时数差
	public static int differHourInTwoCalendar(Calendar timeBefore, Calendar timeAfter) {
		long after = timeAfter.getTimeInMillis();
		long before = timeBefore.getTimeInMillis();
		long differ = (after - before)/(1000 * 60 * 60);
		return (int)differ;
	}
	
	/**
	 * 大写转小写
	 * @param str
	 * @return
	 */
	public static String convertString(String str) {
		return str.toLowerCase();
	}
	
	/**
	 * MD5加密
	 * @param source
	 * @return
	 */
	public static String getMD5(byte[] source) {
		String s = null;
		char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
				'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
			// 所以表示成 16 进制需要 32 个字符
			int k = 0; // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
				// 转换成 16 进制字符的转换
				byte byte0 = tmp[i]; // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
				// >>> 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
			}
			s = new String(str); // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	/**
	 * 验证email是否合法
	 * @param mail
	 * @return
	 */
	public static boolean checkEmail(String mail) {
		String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(mail);
		return m.find();
	}
	//给一个Calendar 加一个 天数
	
	public static boolean isValidPara(String sql)
	{
		if(StringUtil.isEmpty(sql))
			return false;
		if(sql.contains("'"))
		{
			return false;
		}
		return true;
	}
}
